
package com.apes.fn.crm.ReturnVisit.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.fn.crm.ReturnVisit.repository.VisitCustomerExpandRepository;
import com.apes.fn.crm.customer.FnCustomer;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.*;

/**
 * 售后回访单
 *
 * @author bbyford
 * @create 2020-2-5
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ReturnVisit.CONST_TABLE_NAME)
public class ReturnVisit extends Model {
    public static final String CONST_TABLE_NAME = "fn_return_visit";

    @Id
    @Comment("单号")
    @Column(name = "id", nullable = false, length = 32)
    @ApesGenerator(code = "fn_return_visit", name = "售后回访单", prefix = "H%(yy)%(month)", padding = 5, useDateRange=true)
    private String id;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    @Comment("回访人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "visitor_id", referencedColumnName = "id")
    private PartyRole visitor;

    @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE},fetch=FetchType.LAZY)
    @JoinTable(name = "fn_return_visit_visitor",
            joinColumns = {@JoinColumn(name = "return_visit_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "visitor_id", referencedColumnName = "id")}
    )
    private List<PartyRole> visitors = new ArrayList<>(); //回访人员

    @Comment("门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;

    @States(name = "单据状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "again", name = "继续回访"),
            @State(id = "end", name = "终止"),
            @State(id = "finish", name = "回访完成")})
    @Column(name = "state", length = 16, nullable = false)
    private String state = "create";


    @Transient
    private String stateName;

    public String getStateName() {
        switch (this.state) {
            case "create":
                return "创建";
            case "again":
                return "继续回访";
            case "end":
                return "终止";
            case "finish":
                return "回访完成";
            default:
                return "";
        }
    }

    @Comment("应回访日期")
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "should_visit_date")
    private Date shouldVisitDate;


    @Comment("下次回访日期")
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "next_visit_date")
    private Date nextVisitDate;


    @Comment("回访日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "visited_date")
    private Date visitedDate;

    @Comment("客户手机号")
    @Column(name = "mobile", length = 32)
    private String mobile;


    @Comment("会员身份名称")
    @Column(name = "customer_Role_name", length = 32)
    private String customerRoleName;

    @Comment("会员姓名")
    @Column(name = "realname", length = 32)
    private String realname;

    @Comment("会员等级名称")
    @Column(name = "customer_level_name", length = 32)
    private String customerLevelName;


    @Transient
    private String carLicenses;

    public String getCarLicenses() {
        if (this.returnVisitItems.isEmpty()) return "";
        String[] strings = this.returnVisitItems.stream()
                .filter(returnVisitItem -> returnVisitItem.getCustomerExpand() != null && !returnVisitItem.getCustomerExpand().getCarLicense().equals(""))
                .map(returnVisitItem -> returnVisitItem.getCustomerExpand().getCarLicense())
                .distinct().toArray(String[]::new);
        return String.join(",", strings);
    }


    @Transient
    private Enumeration visitPeriod;

    public Enumeration getVisitPeriod() {
        VisitCustomerExpand visitCustomerExpand = SpringManager.getBean(VisitCustomerExpandRepository.class).findOne(JpaDsl.toCriteriaByEq(
                "mobile", mobile,
                "accessProvider.id", getAccessProvider().getId()
        )).orElse(null);
        return visitCustomerExpand != null ? visitCustomerExpand.getVisitPeriod() : null;
    }

    @Transient
    private AccessProvider accessProvider;

    public AccessProvider getAccessProvider() {
        return company != null ? SpringManager.getBean(AccessProviderRepository.class).findByCompany(company.getId()) : null;
    }


    /***
     * 功能： 售后回访明细
     */
    @OneToMany(mappedBy = "returnVisit", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ReturnVisitItem> returnVisitItems = new ArrayList();

    public List<ReturnVisitItem> getReturnVisitItems() {
        if (returnVisitItems == null) return null;
        for (ReturnVisitItem item : returnVisitItems) {
            item.setReturnVisit(this);
            item.setCompany(this.company);
        }
        return returnVisitItems;
    }


    /**
     * 配合前端展示回访记录
     */

    @Transient
    private Map visitHistory;

    public Map getVisitHistory() {
        if (mobile == null || company == null) return null;
        return MapUtil.mapper(
                "mobile", mobile,
                "companyId", company.getId(),
                "name", "回访记录"
        );
    }

    /**
     * 配合前端展示投诉记录
     */

    @Transient
    private Map complainHistory;

    public Map getComplainHistory() {
        if (mobile == null || company == null) return null;
        return MapUtil.mapper(
                "mobile", mobile,
                "companyId", company.getId(),
                "name", "投诉记录"
        );
    }

    /***
     * 配合前端展示销售明细
     */
    @Transient
    private Map retailOrderItem;

    public Map getRetailOrderItem() {
        if (returnVisitItems == null || returnVisitItems.size() == 0) return null;
        return MapUtil.mapper(
                "name", "销售明细",
                "ids", String.join(",",
                        this.getReturnVisitItems().stream().map(returnVisitItem -> returnVisitItem.getSource())
                                .distinct().toArray(String[]::new)
                )
        );
    }

    @Transient
    private Map customer;

    public Map getCustomer() {
        if (mobile == null || company == null) return null;
        FnCustomerExpand customerExpand = getReturnVisitItems().get(0).getCustomerExpand();
        return MapUtil.mapper(
                "mobile", mobile,
                "realname", customerExpand.getRealname() != null ? customerExpand.getRealname() : "",
                "companyId", company.getId(),
                "levelName", customerExpand.getCustomerLevelName() != null ? customerExpand.getCustomerLevelName() : "",
                "accessProviderId", company.queryAccessProvider().getId(),
                "source",getReturnVisitItems().get(0).getSource() != null ? getReturnVisitItems().get(0).getSource() : ""
        );
    }

}


